<template>
  <div class="view-wrapper">
    <div class="tabs-body">
      <div class="view-inner-wrap">
        <div class="title">{{title}}</div>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" :disabled="disabled">
          <div class="v-title">活动基本信息</div>
            <el-form-item label="活动名称：" prop="name" :key="1" class="activityNameClass">
                <el-input type="text" v-model="ruleForm.name" placeholder="请填写活动名称" maxlength="50" show-word-limit></el-input>
            </el-form-item>

            <el-form-item label="活动时间：" prop="date" :key="2"> 
                <el-date-picker
                  :unlink-panels="true"
                  v-model="ruleForm.date"
                  @change="getTime"
                  type="datetimerange"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  placeholder="选择日期时间">
                </el-date-picker>
              </el-form-item>

              <div class="shopClass">
                <div class="shop_class_item">
                  <div class="shop_class_title">店铺名称：</div>
                  <el-select v-model="shopId" filterable placeholder="请选择" @change="changeShop" >
                    <el-option v-for="itema in shopSeleteList" :key="itema.id" :label="itema.value" :value="itema.id"></el-option>
                  </el-select>
                </div>
                <div class="shop_class_item">
                  <div class="shop_class_title">卡名称：</div>
                  <el-select v-model="cardNameIdList" filterable multiple placeholder="请选择" :disabled="shopId == ''" >
                    <el-option v-for="itema in cardNameList" :key="itema.id" :label="itema.value" :value="itema.id"></el-option>
                  </el-select>
                </div>
                 <el-button type="primary" @click="addblockName" :loading="addblockLoading" :disabled="shopId == '' || cardNameIdList.length == 0 ">添加</el-button>
              </div>
              <el-form-item  prop="shopCardList" :key="3"> 
              <el-table :data="ruleForm.shopCardList" stripe border>
                  <!-- <el-table-column label="序号" type="index" width="55" align="center" fixed /> -->
                  <el-table-column label="店铺名称" align="center" prop="shopName" :show-overflow-tooltip="true" />
                  <el-table-column label="卡名称" align="center" prop="cardName" :show-overflow-tooltip="true" />
                  <el-table-column label="卡功能" align="center"  :show-overflow-tooltip="true" >
                    <template slot-scope="scope" >
                      <dict-tag :options="cardFunction" :value="scope.row.type" />
                      </template>
                  </el-table-column>
                  <el-table-column label="发行方" align="center" prop="issuerName" :show-overflow-tooltip="true" />
                  <el-table-column label="发行店铺" align="center" prop="shopName" :show-overflow-tooltip="true" />
                  <el-table-column label="上链时间" align="center" prop="issueTime" :show-overflow-tooltip="true" width="160"/>
                  <el-table-column label="售价" align="center" prop="price" :show-overflow-tooltip="true" />
                  <el-table-column label="库存总量" align="center" prop="total" :show-overflow-tooltip="true" />
                  <el-table-column label="剩余库存" align="center" prop="usable" :show-overflow-tooltip="true" />
                  <el-table-column label="资产状态" align="center"  :show-overflow-tooltip="true" >
                    <template slot-scope="scope" >
                      <dict-tag :options="assetStatusList" :value="scope.row.sellStatus" />
                      </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
                      <template slot-scope="scope" >
                        <el-button size="mini" type="text" @click="handleDel(scope.$index,scope.row)">删除</el-button>
                      </template>
                    </el-table-column>
              </el-table>
              </el-form-item>
              <div class="v-title">激励规则</div>

              <el-form-item label="激励规则：" prop="incentiveType" :key="5"> 
                  <el-select v-model="ruleForm.incentiveType" placeholder="请选择" :disabled="pathType == 'edit'">
                    <el-option v-for="itema in incentiveRulesList" :key="itema.id" :label="itema.value" :value="itema.id"> </el-option>
                  </el-select>
              </el-form-item>
              <el-form-item label="积分类型：" prop="integralType" :key="6"> 
                  <el-select v-model="ruleForm.integralType" placeholder="请选择" :disabled="pathType == 'edit'">
                    <el-option v-for="itema in incentiveTypeList" :key="itema.id" :label="itema.value" :value="itema.id"> </el-option>
                  </el-select>
              </el-form-item>

              <div class="ruleList">
                  <div class="clockInRulesTitle">打卡规则</div>
                  <el-button type="primary" @click="addClockInTime" :disabled="pathType == 'edit'">新增</el-button>
              </div>
              <div class="rowList" v-for="(item,index) in ruleForm.ruleList" :key="index+'c'">
                  <div>
                    <el-form-item label="打卡时间:"  :prop="'ruleList.'+index+'.punchTime'" :rules="rules.punchTime" :key="7" >
                    <el-input type="text" placeholder="请输入打卡限制时间" v-model="item.punchTime" @input="checkPosInteger($event, index)" :disabled="pathType == 'edit'">
                      <template slot="append">小时内</template>
                    </el-input>
                  </el-form-item>
                  <el-form-item :label="ruleForm.incentiveType == 2?'激励金额:':'激励比例:'"  :prop="'ruleList.'+index+'.incentiveAmount'" :rules="ruleForm.incentiveType == 2?rules.incentiveAmount:rules.incentiveRatio" :key="ruleForm.incentiveType == 2?8:9" :disabled="pathType == 'edit'">
                    <el-input type="text" placeholder="请输入" v-model="item.incentiveAmount" @input="checkIncentiveAmount($event, index)" :disabled="pathType == 'edit'">
                      <template slot="append" v-if="ruleForm.integralType != ''">{{ruleForm.incentiveType == 2?(ruleForm.integralType == 1?'CoCo':'椰分'):'%'}}</template>
                    </el-input>
                  </el-form-item>
                  </div>
                  <div class="btnBox">
                    <el-button type="danger" icon="el-icon-delete" circle @click="deletePunch(index)" v-if="index != 0" :disabled="pathType == 'edit'"></el-button>
                  </div>
              </div>
           <el-form-item class="fFooter">
            
            <el-button type="primary" @click="submitForm('ruleForm',1)" :loading="loading" v-if="ruleForm.status == 1 || pathType == 'add'">保存草稿</el-button>
            <el-button type="primary" @click="submitForm('ruleForm',2)" :loading="loading">{{pathType == 'edit'?'保存修改':'保存提交'}}</el-button>
            <el-button type="primary" @click="cancelForm()">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    
  </div>
</template>
<script>
import {
  getShopSelect,
  getShopCardSelect,
  getShopCardId,
  addShenyeLimitTime,
  shenyeLimitTimeDetail,
  editShenyeLimitTime,
} from '@/api/blindBox/timeLimitActivities'
export default {
  name: "",
  components: {
    
  },
  
  data() {
    return {
      title: '新增限时打卡活动',
      //激励规则
      incentiveRulesList:[
        {id: '1',value: '按交易金额比例激励',},
        {id: '2',value: '按固定金额激励'},
      ], 
      //积分类型
      incentiveTypeList: [
        {id: '1',value: 'CoCo',},
        {id: '2',value: '椰分',},
      ],
      shopSelete:[],//店铺下拉
      disabled: false,
      addblockLoading: false, //添加卡名称下拉
      pathType: 'add',
      loading: false,
      shopId:'', //店铺id
      shopSeleteList:[],//店铺名称列表
      cardNameIdList:[], //卡名称ID列表
      cardNameList:[], //卡名称列表
      cardFunction:[],//卡功能列表
      assetStatusList:[],//资产状态列表
      ruleForm: {
        name:'',//活动名称
        startTime:'',//活动开始时间
        endTime:'',//活动结束时间
        date: [], //活动时间
        shopCardList:[],//店铺卡名称列表
        incentiveType:'',//激励规则
        integralType:'',//激励类型
        // 按交易金额比例激励
        ruleList:[
          {
            punchTime:'',//打卡时间
            incentiveAmount:'',//激励比例
          }
        ],
      },
      rules: {
        name:[
          { required: true, message: '请输入活动名称', trigger: 'blur' },
        ],
        date: [
          { required: true, message: '请选择日期', trigger: 'change' }
        ],
        // shopName: [
        //   { required: true, message: '请输入店铺名称', trigger: 'blur' },
        // ],

        shopCardList:[
          { required: true, message: '请添加卡名称列表', trigger: ['blur','change'] },
        ],
        incentiveType:[
          { required: true, message: '请选择激励规则', trigger: 'change' },
        ],
        integralType:[
          { required: true, message: '请选择积分类型', trigger: 'change' },
        ],
        punchTime:[
          { required: true, message: '请输入打卡限制时间', trigger: ['blur','change'] },
        ],
        incentiveRatio:[
          { required: true, message: '请输入激励比例', trigger: ['blur','change'] },
        ],
        incentiveAmount:[
          { required: true, message: '请输入激励金额', trigger: ['blur','change'] },
        ],
      }
      
    };
  },
  watch: {
   
  },
  created() {
    this.pathType = this.$route.query.pathType
    this.ruleForm.id = this.$route.query.id
    this.getadminDict()
    this.getShopSelectList()
    if(this.pathType == 'edit'){
      this.title = '编辑限时打卡活动'
      this.getDetail()
    }else if(this.pathType == 'add'){
      this.title = '新增限时打卡活动'
    }
  },
  mounted() {
  
  },
  methods: {
    getadminDict() {
      //获取商户类型字典
      var dictType = "merchant_equity_card_type,merchant_equity_card_sell_status";
      this.$getSelectList(dictType)
          .then((res) => {
            this.cardFunction = res.result[0].dictList;
            this.assetStatusList = res.result[1].dictList;
          })
      },
    //获取店铺下拉
    getShopSelectList(){
      getShopSelect().then(res => {
        this.shopSeleteList = res.result
      })
    },
    //获取卡名称下拉
    getShopCardSelectList(){
      var merchantEquityCardIdList = this.getfilterateId(this.ruleForm.shopCardList)
      var data = {
        merchantId:this.shopId,
        merchantEquityCardIdList:merchantEquityCardIdList
      }
      getShopCardSelect(data).then(res => {
        this.cardNameList = res.result
      })
    },
  //选择店铺
    changeShop(e){
      this.getShopCardSelectList()
    },
    // 添加卡类型
    addblockName(){
      var data = {
        merchantEquityCardIdList:this.cardNameIdList
      }
      this.addblockLoading = true
      getShopCardId(data).then(res=>{

        setTimeout(()=>{
          this.$message.success('添加成功')
          this.addblockLoading = false
          this.shopId = ''
          this.cardNameIdList = []
          this.cardNameList = []

          this.ruleForm.shopCardList = 
          [
            ...this.ruleForm.shopCardList,
            ...res.result
          ]
          this.$refs.ruleForm.clearValidate('shopCardList')
        },1000)

      }).catch(error=>{
        this.addblockLoading = false
      })
    },
    // 过滤 数组返回id集合
    getfilterateId(arr){
      var newArr2=arr.map((v)=> v.merchantEquityCardId).join();
      return newArr2
    },
    // 输入激励比例、激励金额限制输入
    checkIncentiveAmount(value,index){
      var data = this.limitNum(value)
      this.ruleForm.ruleList[index].incentiveAmount = data
    },
    // 大于0的正整数，可限制整数位
    checkPosInteger(value, index) {
      var integerMax = 4
      let reg = new RegExp(`^(\\d{${integerMax}}).*$`)
      var data =  value.replace(/^(0+)|[^\d]+/g, '').replace(reg, '$1')
      this.ruleForm.ruleList[index].punchTime = data
    },
    // 必须大于0，最多小数点后两位
    limitNum(amount) {
        amount = amount
        .replace(/[^\d.]/g, "") //只能输入数字
        .replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3") //只能输入两个小数
        .replace(/\.{2,}/g, "."); //出现多个点时只保留第一个
      // 第一位不让输小数点
      if (amount == ".") {
        amount = "";
      }
      // 如果第一位是0，第二位必须大于0或者小数点
      if (amount.substring(0, 1) == 0) {
        if (amount.substring(1, 2) > 0) {
          amount = amount.substring(1, 2);
        } else if (
          amount.substring(1, 2) === 0 ||
          amount.substring(1, 2) === "0"
        ) {
          amount = "0";
        }
      } else {
        // 如果第一位数字大于0（不等于0肯定就大于0），仅需考虑第二位是小数点的情况
        if (amount.indexOf(".") !== -1) {
          if (amount.substring(0, 1) > 0) {
            console.log("第一位大于0");
          } else {
            console.log("第一位等于0");
            if (amount.substring(2, 3) > 0) {
              console.log("小数点后第一位大于0");
            } else {
              console.log("小数点后第一位等于0");
              amount = "0.";
            }
          }
        } else {
          console.log("没有小数点，正常输入");
        }
      }
      // 
      return amount
    },
    //卡名称列表移除标签
    // removeTag(e){
    //   var isShow = this.ruleForm.blockNameList.findIndex(item=>item.id == e.id)
    //   if(isShow > -1){
    //     this.ruleForm.blockNameList.splice(isShow,1)
    //   }
    // },
    // 删除卡名称列表
    handleDel(index,row){
      this.$confirm('是否删除', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log(index)
          this.ruleForm.shopCardList.splice(index,1)
        }).catch(() => {});
    },

    //格式化选择时间
    getTime(e){
      // console.log(e)
      if(e!= null){
        this.ruleForm.startTime =  e[0]
        this.ruleForm.endTime = e[1] 
      }

    },
    //获取详情
    getDetail() {
      shenyeLimitTimeDetail(this.ruleForm.id).then(response => {
        this.ruleForm = response.result
        this.$set(this.ruleForm,'date',[this.ruleForm.startTime,this.ruleForm.endTime])
      });
    },
    //添加打卡规则
    addClockInTime(){
      var obj = {
          punchTime:'',//打卡时间
          incentiveAmount:'',//激励比例
        }
      this.ruleForm.ruleList.push(obj)    
    },
    //删除打卡规则
    deletePunch(index){
      this.ruleForm.ruleList.splice(index,1)
    },
    // 取消
    cancelForm(){
      this.$router.go(-1)
    },
    submitForm(formName,saveStatus) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
           this.loading = true
           var data = {
              ...this.ruleForm
            }
            data.saveStatus = saveStatus
            delete data.date
          if(this.pathType == 'add'){
            addShenyeLimitTime(data).then(res => {
              this.$message.success('创建成功')
              this.$router.push({
                path: '/blindBox/timeLimitActivities-List'
              })
              setTimeout(() => {
                this.loading = false
              }, 5000);
            }).finally(() => {
              this.loading = false
            })
          }else if(this.pathType == 'edit'){
            editShenyeLimitTime(data).then(res => {
              this.$message.success('修改成功')
              this.$router.push({
                path: '/blindBox/timeLimitActivities-List'
              })
               setTimeout(() => {
                this.loading = false
              }, 1000);
            }).finally(() => {
              this.loading = false
            })
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.tabs-body {
  background-color: #fff;
  padding: 20px 0;
}
.title{
  font-size: 24px;
  padding: 14px 30px 14px 14px;
  margin-bottom: 14px;
  color: #222;
  font-weight: bold;
  // border-bottom: 1px solid #DCDFE6;
}
::v-deep{
  .el-form{
    padding: 0 20px;
    .el-input{
      width: 350px;
    }
    .el-table{
      margin-bottom: 20px;
    }
    .v-title{
      padding: 10px 0;
      width: 50%;
      border-bottom: 1px solid #DCDFE6;
      margin-bottom: 20px;
      font-size: 17px;
      font-weight: 600;
    }
    .activityNameClass{
      .el-input__suffix  {
        right: -45px;
      }
    }
    .ruleList{
      width: 620px;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;
      .clockInRulesTitle{
        font-size: 15px;
        &::before{
          content: "*";
          color: #ff4949;
          margin-right: 4px;
        }
      }
    }
    .rowList{
      width: 620px;
      box-sizing: border-box;
      padding: 20px 20px 20px 20px;
      border: 1px solid #DCDFE6;
      border-radius: 10px;
      margin-top: 20px;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      .btnBox{
          width: auto;
          margin-left: 20px;
        }
     }
     .fFooter{
       margin-top: 40px;
     }
     .shopClass{
        display: flex;
        flex-direction: row;
        align-items: flex-start;
        margin-bottom: 22px;
        .shop_class_item{
          display: flex;
          flex-direction: row;
          align-items: center;
          margin-right: 20px;
          .shop_class_title{
            font-size: 14px;
            color: #606266;
            line-height: 40px;
            padding: 0 12px 0 0;
            &::before{
              content: "*";
              color: #ff4949;
              margin-right: 4px;
            }
          }
        }
     }
  }
} 

</style>
